var util = require('../../utils/util.js');
Page( {
  data: {
    totalPrice: 0,
    cartList: [],
    user: null,
    order: null,
    address: null,
    selectAll: true,
    ispayed: false,
  },

  onLoad: function(e) {
    var user = wx.getStorageSync('user');
    if (user == '' || user.uid == '') {
      wx.showModal({ content: '数据加载失败，请重新进入！', showCancel: false });
      return;
    }
    this.setData({ user: user });
    var data = JSON.parse(e.data);
    console.log('传参', data);
    var cartList = [data];
    var totalPrice = 0;
    for(var i = 0; i < cartList.length; i ++) {
      cartList[i]['checked'] = true;
      totalPrice += cartList[i].price * cartList[i].count;
    }
    this.setData({ order: data, cartList: cartList, totalPrice: totalPrice.toFixed(2) });
    this.showAddress();
  },

  submit: function(e) {
    var address = this.data.address;
    if (address == null || address.id == null || address.id =='') {
      wx.showModal({ content: '请添加一个收货地址！', showCancel: false });
      return;
    }
    // 订单数据
    var order = this.data.order;
    if(order != null) {
      order["uid"] = this.data.user.uid;
      order["addressId"] = address.id;
      order["appId"] = 'wx0b236a02a79e42f7';
      // 后台传入支付总价
      order.totalPrice = this.data.totalPrice;
      console.log('订单数据', order)
      
      this.setData({ ispayed: true });
      wx.request({
        url: util.requestUrl.toPay,
        method: 'POST',
        data: order,
        header: { 'content-type': 'application/json' },
        success: res => {
          console.log('生成订单', res);
          if (res.data.success) {
            this.wxpay(res.data.payment);
          }
        },
        fail: res => {
          console.log('fail', res);
          this.setData({ ispayed: false });
        }
      });
    }
  },

  wxpay: function (result) {
    wx.requestPayment({
      timeStamp: result.timeStamp,
      nonceStr: result.nonceStr,
      package: result.package,
      signType: result.signType,
      paySign: result.paySign,
      success: function (res) {
        // 成功则弹出输入密码
        console.log('success', res);
        if (res.errMsg == 'requestPayment:ok') {
          wx.showModal({ content: '支付成功，商家将在48小时内为您发货！', showCancel: false });
          wx.redirectTo({ url: '/pages/order/order' });
        }
      },
      fail: res => {
        console.log('用户取消支付');
        // 设置按钮可点击
        this.setData({ ispayed: false });
      },
      complete: res => {
        console.log('complete', res);
        // 取消支付
        if (res.errMsg == 'requestPayment:fail cancel') {
          // 设置按钮可点击
          this.setData({ ispayed: false });
        }
      }
    });
  },

  /**
   * 购买数量加减操作
   */
  buyNum: function (e) {
    var id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    var cartList = this.data.cartList;
    var buyNum = parseInt(cartList[id].count);
    if (type == -1 && buyNum == 1) return;
    buyNum = (type == -1 && buyNum > 1) ? (buyNum - 1) : (buyNum + 1);
    cartList[id].count = buyNum;
    this.setCartList(cartList);
  },

  // 输入数量
  inputNum: function (e) {
    var num = e.detail.value;
    if (isNaN(num) || num <= 0) return;
    var id = e.currentTarget.dataset.id;
    var cartList = this.data.cartList;
    cartList[id].count = num;
    this.setCartList(cartList);
  },

  /**
   * 设置购物车数据
   */
  setCartList: function (cartList) {
    var totalPrice = 0;
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].checked) {
        totalPrice += cartList[i].price * cartList[i].count;
      }
    }
    var order = this.data.order;
    order.count = cartList[0].count;
    this.setData({ cartList: cartList, totalPrice: totalPrice.toFixed(2) });
  },

  showAddress: function() {
    wx.request({
      url: util.requestUrl.addressList,
      method: 'GET',
      data: { "uid": this.data.user.uid },
      header: { 'content-type': 'application/json' },
      success: res => {
        console.log(res);
        var result = res.data;
        if (result.success) {
          if (result.list.length > 0) {
            this.setData({ address: result.list[0] });
          }
        }
      }
    })
  },

  // 点击进入选择/新增地址
  editAddress: function() {
    wx.chooseAddress({
      success: res => {
        this.saveAddress(res);
      },
      fail: function(res) {
        console.log('fail', res);
      }
    });
  },

  saveAddress: function (formData) {
    console.log('formData', formData);
    if (formData.provinceName.indexOf('新疆') > -1
     || formData.provinceName.indexOf('西藏') > -1
     || formData.provinceName.indexOf('内蒙古') > -1) {
      wx.showModal({ content: '抱歉，暂不支持该地址配送！', showCancel: false });
      return;
    }
    var data = {
      "uid": this.data.user.uid,
      "phone": formData.telNumber,
      "name": formData.userName,
      "address": formData.provinceName + formData.cityName + formData.countyName + formData.detailInfo,
      "flag": 1
    }
    wx.request({
      url: util.requestUrl.addressSave,
      method: 'POST',
      data: data,
      header: { 'content-type': 'application/json' },
      success: res => {
        console.log('res', res);
        if(res.data.success) {
          data["id"] = res.data.addressId;
          this.setData({ address: data });
        }
      }
    });
  },

  leaveWord: function(e) {
    var order = this.data.order;
    order["comment"] = e.detail.value;
    this.setData({ order: order });
  }

})
